package com.rbac.web.config;

import com.rbac.web.model.User;
import com.rbac.web.model.UserContext;
import com.rbac.web.service.IUserTokenService;
import java.io.IOException;
import java.util.Set;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * @author gengaoliu
 */
@Component
@RequiredArgsConstructor
public class AuthenticationFilter extends OncePerRequestFilter {

  private final IUserTokenService tokenService;

  private static final Set<String> IGNORE_PATHS = Set.of("/swagger-ui/**", "/v3/**", "/sys/**");

  @Override
  protected void doFilterInternal(
      HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
      throws ServletException, IOException {
    String tokenId = request.getHeader(HttpHeaders.AUTHORIZATION);
    if (null == tokenId) {
      response.sendError(HttpStatus.UNAUTHORIZED.value(), "请先登陆");
    }
    boolean b = tokenService.haveToken(tokenId);
    if (!b) {
      response.sendError(HttpStatus.UNAUTHORIZED.value(), "当前token不存在,请登录");
      return;
    }
    User user = tokenService.getUser(tokenId);
    if (user == null) {
      response.sendError(HttpStatus.UNAUTHORIZED.value(), "登录已失效");
      return;
    }
    UserContext.set(user);
    filterChain.doFilter(request, response);
  }

  @Override
  protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
    String uri = request.getRequestURI();
    return IGNORE_PATHS.stream().anyMatch(path -> new AntPathMatcher().match(path, uri));
  }
}
